//
//  PhotoWriter.swift
//  Combinestagram
//
//  Created by infoware on 2018/5/24.
//  Copyright © 2018年 infoware. All rights reserved.
//

import Foundation
import UIKit
import RxSwift
import Photos

enum Errors:Error{
    case couldNotSavePhoto
}

class PhotoWriter:NSObject{
    typealias Callback = (NSError?)->Void
    
    static func save(_ image:UIImage) -> Observable<String>{
        return Observable.create({observer in
            var savedAssetId:String?
            
            PHPhotoLibrary.shared().performChanges({
                let request = PHAssetChangeRequest.creationRequestForAsset(from: image)
                savedAssetId = request.placeholderForCreatedAsset?.localIdentifier
            }, completionHandler: { (success, error) in
                DispatchQueue.main.async {
                    if success, let id = savedAssetId {
                        observer.onNext(id)
                        observer.onCompleted()
                    } else {
                        observer.onError(error ?? Errors.couldNotSavePhoto)
                    }
                }
            })
            
           return Disposables.create()
        })
    }
}
